﻿/*========================== 
 * @author 郑金泉
 * @desc SQL JOIN 条件类
 * ========================= */
using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Edm;

namespace Obsidian.Data.Sql
{
    public class JoinClause
    {

        private JoinType _joinType = JoinType.Inner;
        private IModel _model = null;
        private bool _isUsing = false;
        private CompoundCondition _onCondition = new CompoundCondition();

        public JoinClause(IModel model, JoinType joinType)
        {
            if (model == null)
                throw new Exception("参数model不能为null");
            this._model = model;
            this._joinType = joinType;
        }

        public JoinType Type
        {
            get { return this._joinType; }
        }

        public IModel Model
        {
            get { return this._model; }
        }

        public bool IsUsing
        {
            get { return this._isUsing; }
        }

        public JoinClause On(ISqlCondition sqlCondition)
        {
            this._onCondition.AddSubCondition(sqlCondition);
            return this;
        }

        public string BuildSqlText()
        {
            StringBuilder sb = new StringBuilder();
            switch(this.Type)
            {
                case JoinType.Inner:
                    sb.Append(" INNER JOIN ");
                    break;
                case JoinType.Left:
                    sb.Append(" LEFT JOIN ");
                    break;
                case JoinType.LeftOuter:
                    sb.Append(" LEFT OUTER JOIN ");
                    break;
                case JoinType.Right:
                    sb.Append(" RIGHT JOIN ");
                    break;
                case JoinType.RightOuter:
                    sb.Append(" RIGHT OUTER JOIN ");
                    break;
            }
            DataBaseType dbType = this.Model.GetDataBase().Type;
            if (dbType == DataBaseType.SqlServer || dbType == DataBaseType.OleDb)
            {
                sb.Append("[")
                    .Append(this.Model.DbTableName)
                    .Append("]");
            }
            else if (dbType == DataBaseType.MySql)
            {
                sb.Append("`")
                    .Append(this.Model.DbTableName)
                    .Append("`");
            }
            else
            {
                throw new Exception("未知数据库类型");
            }
            sb.Append(" ON ");

            if (this._onCondition.SubConditions.Count > 1)
                sb.Append("(");

            sb.Append(this._onCondition.BuildSqlText());

            if (this._onCondition.SubConditions.Count > 1)
                sb.Append(")");

            return sb.ToString();
        }

    }

    public enum JoinType
    {
        Inner,
        Left,
        Right,
        LeftOuter,
        RightOuter
    }

}
